package com.zhonghui.modlules.user.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eshop.apiCode.EshopException;
import com.zhonghui.common.bean.LocalUser;
import com.zhonghui.common.eshopConstant.ShopConstants;
import com.zhonghui.common.eshopDomain.ShopUser;
import com.zhonghui.common.eshopEnum.BillDetailEnum;
import com.zhonghui.common.eshopUtil.ApiResult;
import com.zhonghui.modlules.shop.eshopDomain.SystemGroupData;
import com.zhonghui.modlules.shop.eshopDto.SystemGroupDataQueryCriteria;
import com.zhonghui.modlules.shop.eshopService.SystemGroupDataService;
import com.zhonghui.modlules.shop.eshopVo.SystemGroupDataVo;
import com.zhonghui.modlules.user.eshopDomain.UserBill;
import com.zhonghui.modlules.user.eshopService.UserBillService;
import com.zhonghui.modlules.user.eshopService.UserRechargeService;
import com.zhonghui.modlules.user.eshopService.UserService;
import com.zhonghui.modlules.user.param.RechargeParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "用户充值", tags = "用户:用户充值", description = "用户充值")
public class UserRechargeController {
// 不熟
    private final UserService userService;
    private final UserBillService userBillService;
    private final UserRechargeService rechargeService;
    private final SystemGroupDataService systemGroupDataService;

    @ApiOperation(value = "充值方案",notes = "充值方案")
    @GetMapping("/recharge/index")
    public ApiResult<Object> rechargeWays(){
        SystemGroupDataQueryCriteria queryCriteria = new SystemGroupDataQueryCriteria();
        queryCriteria.setGroupName(ShopConstants.YSHOP_RECHARGE_PRICE_WAYS);
        List<SystemGroupData> systemGroupData = systemGroupDataService.queryAll(queryCriteria);

            List<SystemGroupDataVo>  groupDataVos = systemGroupData.stream().map(s -> {
            SystemGroupDataVo systemGroupDataVo = new SystemGroupDataVo();
            /**
             * BeanUtils.copyProperties(a, b);
             * b中的存在的属性，a中一定要有，但是a中可以有多余的属性；
             * a中与b中相同的属性都会被替换，不管是否有值；
             * a、 b中的属性要名字相同，才能被赋值，不然的话需要手动赋值；
             */
            // s：转化前的类（systemGroupData）  systemGroupDataVo：转换后的类  第三个的参数：忽略的值
            BeanUtil.copyProperties(s, systemGroupDataVo, "value");
            systemGroupDataVo.setValue(JSON.parseObject(s.getValue()));

            return systemGroupDataVo;
        }).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("rechargePriceWays",groupDataVos);
        return ApiResult.ok(map);
    }

    @ApiOperation(value = "模拟充值",notes = "模拟充值")
    @PostMapping("/recharge/test")
    public ApiResult<String> rechargeTest(@Valid RechargeParam rechargeParam){
        ShopUser shopUser = LocalUser.getUser();
        SystemGroupData systemGroupData = systemGroupDataService.getById(rechargeParam.getRecharId());
        if (systemGroupData  == null){
            throw new EshopException("充值方案不存在");
        }
        // 数据组(price、give_price)对应的数据值(在user_recharge表内)
        JSONObject jsonObject = JSON.parseObject(systemGroupData.getValue());
        String price = jsonObject.getString("price");
        String giveMoney = jsonObject.getString("give_price");

        String orderSn = rechargeService.addRecharge(shopUser, price, giveMoney);
        if (orderSn != null){
            BigDecimal new_price = new BigDecimal(price);
            BigDecimal new_giveMoney = new BigDecimal(giveMoney);

            BigDecimal total = new_price.add(new_giveMoney);
            BigDecimal balance = shopUser.getNowMoney().add(total);

            shopUser.setNowMoney(balance);
            userService.updateById(shopUser);

            UserBill userBill = new UserBill();
            userBill.setUid(shopUser.getUid());
            userBill.setTitle("账户充值");
            userBill.setCategory(BillDetailEnum.CATEGORY_1.getValue());
            userBill.setType(BillDetailEnum.TYPE_1.getValue());
            userBill.setPm(1);
            userBill.setNumber(total);
            userBill.setBalance(balance);
            userBill.setMark("模拟充值：充值"+new_price+"元赠送"+new_giveMoney+"元");
            userBillService.save(userBill);
        }
        return ApiResult.ok("充值成功");
    }
}
